package com.hopes.bizz.poll.hj212.server.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hopes.bizz.poll.common.constant.enums.PollModDictEnum;
import com.hopes.bizz.poll.hj212.beans.bo.HJ212MainAttrBO;
import com.hopes.bizz.poll.hj212.constant.HJ212Constant;
import com.hopes.bizz.poll.monitor.service.PollMonitorSiteService;
import com.hopes.bizz.poll.om.entity.BaseOmDataEntity;
import com.hopes.bizz.poll.om.service.*;
import com.hopes.bizz.poll.pollaqi.entity.Aqi;
import com.hopes.boss.admin.api.resolver.DictResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 污染源在线监控数据解析
 */
@Component
@Slf4j
public class OnlineMonitorDataHandler extends AbstractHJ212DataHandler {
    @Autowired
    protected PollOriginalDataService originalDataService;
    @Autowired
    protected PollRtDataService rtDataService;
    @Autowired
    protected PollMinService minService;
    @Autowired
    protected PollHourService hourService;
    @Autowired
    protected PollDayService dayService;
    @Autowired
    private PollMonitorSiteService pollMonitorSiteService;
    @Autowired
    protected PollRtDataHisService pollRtDataHisService;

    @Override
    public void handlerRealTimeData(Long monitorSiteId, JSONObject dataJson, String data, HJ212MainAttrBO mainAttrBO) {
        buildAndSaveMonitorData(rtDataService, monitorSiteId, dataJson, data, mainAttrBO);
    }

    @Override
    public void handlerMinuteData(Long monitorSiteId, JSONObject dataJson, String data, HJ212MainAttrBO mainAttrBO) {
        buildAndSaveMonitorData(minService, monitorSiteId, dataJson, data, mainAttrBO);
    }

    @Override
    public void handlerHourData(Long monitorSiteId, JSONObject dataJson, String data, HJ212MainAttrBO mainAttrBO) {
        buildAndSaveMonitorData(hourService, monitorSiteId, dataJson, data, mainAttrBO);
    }

    @Override
    public void handlerDayData(Long monitorSiteId, JSONObject dataJson, String data, HJ212MainAttrBO mainAttrBO) {
        buildAndSaveMonitorData(dayService, monitorSiteId, dataJson, data, mainAttrBO);
    }

    /**
     * 构建并保存监控数据
     *
     * @param omHJ212DataService
     * @param monitorSiteId
     * @param dataMap
     * @param data
     * @param mainAttrBO
     */
    private void buildAndSaveMonitorData(OmHJ212DataService omHJ212DataService, Long monitorSiteId, JSONObject dataMap, String data, HJ212MainAttrBO mainAttrBO) {
        // 保存原始数据
        originalDataService.saveOriginalData(data);

        JSONObject dataJson = buildMonitorDataWithJson(dataMap);
        if (dataJson != null) {
            BaseOmDataEntity omData = new BaseOmDataEntity();
            initOmData(mainAttrBO, omData, monitorSiteId, dataJson);

            synchronized (OnlineMonitorDataHandler.class) {
                // 计算AQI的值
                Double aqiData = computerAQI(omData.getMonitorSiteId(), omData.getDataJson());
                omData.setAqiData(aqiData);
                omHJ212DataService.saveHJ212Data(omData, data);
            }
        } else {
            log.debug("监测数据列表为空，跳过保存操作 data:{}", data);
        }
    }

    private Double computerAQI(Long id, JSONObject data) {
        try {
            // 计算AQI的值（是AQI站点）
            Boolean aqiFlag = pollMonitorSiteService.getById(id).getAqiFlag();
            if (aqiFlag) {
                Aqi aqi = pollRtDataHisService.calculateAQI(data);
                if (ObjectUtil.isNotEmpty(aqi)) {
                    return aqi.getAqi();
                }
            }
            return null;
        } catch (Exception e) {
            log.error("AQI计算出错");
            return null;
        }
    }

    @Override
    protected Long getMonitorSiteIdIfExist(JSONObject dataJson) {
        String monitorSiteId = DictResolver.getItemLabelByValue(PollModDictEnum.monitor_site_mn, dataJson.getString(HJ212Constant.KEY_MN));
        if (monitorSiteId != null) {
            return Long.valueOf(monitorSiteId);
        }
        return null;
    }

    protected Long getMonitorSiteOrgIdIfExist(JSONObject dataJson) {
        String orgId = DictResolver.getItemByValue(PollModDictEnum.monitor_site_mn, dataJson.getString(HJ212Constant.KEY_MN)).getExt2();
        if (orgId != null) {
            return Long.valueOf(orgId);
        }
        return null;
    }

    /**
     * 初始化实时监控数据基础字段
     *
     * @param omData
     * @param monitorSiteId
     */
    private void initOmData(HJ212MainAttrBO mainAttrBO, BaseOmDataEntity omData, Long monitorSiteId, JSONObject dataJson) {
        omData.setMonitorSiteId(monitorSiteId);
        omData.setDataTime(mainAttrBO.getDataTime());
        omData.setMn(mainAttrBO.getMn());
        omData.setDataJson(dataJson);
        omData.setOrgId(mainAttrBO.getOrgId());
    }

    public JSONObject buildMonitorDataWithJson(JSONObject dataJson) {
        JSONObject result = new JSONObject();
        JSONArray jsonArray = dataJson.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            result.put(json.getString("key"), json);
        }
        return result;
    }
}
